package me.nereo.multi_image_selector;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import org.xutils.common.Callback;
import org.xutils.image.ImageOptions;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import me.nereo.multi_image_selector.view.ViewPagerFixed;
import uk.co.senab.photoview.PhotoView;

/**
 * 查看单张图片
 * Created by yiw on 2016/1/6.
 */
public class ImagePagerActivity extends Activity implements View.OnClickListener {
    public static final String INTENT_IMGURLS = "imgurls";
    public static final String INTENT_POSITION = "position";
    private ImageView btn_back;
    private TextView picNum;
    private Button delete;
    private ArrayList<String> imgUrls;
    int currentPosition;
    ImageAdapter mAdapter;

    public static void startImagePagerActivity(Context context, List<String> imgUrls, int position) {
        Intent intent = new Intent(context, ImagePagerActivity.class);
        intent.putStringArrayListExtra(INTENT_IMGURLS, new ArrayList<String>(imgUrls));
        intent.putExtra(INTENT_POSITION, position);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_preview_pic);
        ViewPagerFixed viewPager = (ViewPagerFixed) findViewById(R.id.pager);
        btn_back = (ImageView) findViewById(R.id.btn_back);
        picNum = (TextView) findViewById(R.id.picNum);
        delete = (Button) findViewById(R.id.delete);

        btn_back.setOnClickListener(this);
        delete.setOnClickListener(this);
        imgUrls = getIntent().getStringArrayListExtra(INTENT_IMGURLS);
        int startPos = getIntent().getIntExtra(INTENT_POSITION, 0);
        picNum.setText(1 + startPos + "/" + imgUrls.size());
        mAdapter = new ImageAdapter(this);
        mAdapter.setDatas(imgUrls);
        viewPager.setAdapter(mAdapter);
        viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                currentPosition = position;
                picNum.setText(currentPosition + 1 + "/" + imgUrls.size());
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        viewPager.setCurrentItem(startPos);
    }

    @Override
    public void onClick(View view) {
        int id = view.getId();
        if (R.id.btn_back == id) {
            finshPre();
        }
        if (R.id.delete == id) {
            deletePic();
        }
    }

    private void finshPre() {
        Intent intent = new Intent(this, MultiImageSelectorFragment.class);
        intent.putStringArrayListExtra("imgurls", new ArrayList<String>(imgUrls));
        Log.e("imgUrls", imgUrls.toString());
        this.setResult(120, intent);
        this.finish();
    }

    /**
     * 删除已选择的图片的方法
     */
    private void deletePic() {
        if (imgUrls.size() > 0) {
            imgUrls.remove(currentPosition);
            mAdapter.setDatas(imgUrls);
            mAdapter.notifyDataSetChanged();
            if (imgUrls.size() > 0)
                picNum.setText(currentPosition + 1 + "/" + imgUrls.size());
        }
        if (imgUrls.size() == 0) {
            finshPre();
        }

    }

    private static class ImageAdapter extends PagerAdapter {

        private List<String> datas = new ArrayList<String>();
        private LayoutInflater inflater;
        private ImageOptions options;
        private Context context;

        public void setDatas(List<String> datas) {
            if (datas != null)
                this.datas = datas;
        }

        public ImageAdapter(Context context) {
            this.context = context;
            this.inflater = LayoutInflater.from(context);
            options = new ImageOptions.Builder()
                    // 是否忽略GIF格式的图片
                    .setIgnoreGif(false)
                            // 图片缩放模式
                    .setImageScaleType(ImageView.ScaleType.FIT_CENTER)
                    .setConfig(Bitmap.Config.RGB_565)
                            // 下载中显示的图片
                    .setLoadingDrawableId(R.drawable.default_error)
                            // 下载失败显示的图片
                    .setFailureDrawableId(R.drawable.default_error)
                            // 得到ImageOptions对象
                    .build();
        }

        @Override
        public int getCount() {
            if (datas == null) return 0;
            return datas.size();
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            View view = inflater.inflate(R.layout.item_pager_image, container, false);
            if (view != null) {
                final PhotoView imageView = (PhotoView) view.findViewById(R.id.image); //图片查看器
                //预览imageView
//                final ImageView smallImageView = new ImageView(context);
//                smallImageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
//                ((FrameLayout) view).addView(smallImageView);
                //loading
                final ProgressBar loading = new ProgressBar(context);
                FrameLayout.LayoutParams loadingLayoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                        ViewGroup.LayoutParams.WRAP_CONTENT);
                loadingLayoutParams.gravity = Gravity.CENTER;
                loading.setLayoutParams(loadingLayoutParams);
                ((FrameLayout) view).addView(loading);

                final String imgurl = datas.get(position);
                x.image().bind(imageView, "file:///" + imgurl, options, new Callback.CommonCallback<Drawable>() {
                    @Override
                    public void onSuccess(Drawable result) {
                        loading.setVisibility(View.GONE);
//                        smallImageView.setVisibility(View.GONE);
                    }

                    @Override
                    public void onError(Throwable ex, boolean isOnCallback) {

                    }

                    @Override
                    public void onCancelled(CancelledException cex) {

                    }

                    @Override
                    public void onFinished() {
                        loading.setVisibility(View.GONE);
//                        smallImageView.setVisibility(View.GONE);
                    }
                });
                container.addView(view);
            }
            return view;
        }


        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view.equals(object);
        }

        @Override
        public void restoreState(Parcelable state, ClassLoader loader) {
        }

        @Override
        public Parcelable saveState() {
            return null;
        }

        @Override
        public int getItemPosition(Object object) {
            return POSITION_NONE;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (KeyEvent.KEYCODE_BACK == keyCode) {
            finshPre();
        }
        return super.onKeyDown(keyCode, event);
    }
}
